import requests
import json
from config import Config
import logging
from app.db.models import AlertRule

logger = logging.getLogger(__name__)


class Notifier:
    @staticmethod
    def send_dingtalk(owners, message):
        """发送钉钉预警"""
        text = f"【业务预警】\n负责人电话：{owners}\n{message}"
        payload = {
            "msgtype": "text",
            "text": {"content": text},
            'at': {
                'atMobiles': [owners],
                'isAtAll': False
            }

        }
        try:
            response = requests.post(
                Config.DINGTALK_WEBHOOK,
                data=json.dumps(payload),
                headers={'Content-Type': 'application/json'},
                timeout=5
            )
            if response.status_code != 200:
                logger.error(f"钉钉消息发送失败: {response.text}")
            return response.status_code == 200
        except Exception as e:
            logger.error(f"钉钉消息发送失败: {e}")
            return False

    # @staticmethod
    # def send_voice_call(phone, message):
    #     """发送电话预警（示例）"""
    #     payload = {
    #         "api_key": Config.VOICE_API_KEY,
    #         "phone": phone,
    #         "message": message[:100]  # 限制长度
    #     }
    #     try:
    #         response = requests.post(
    #             Config.VOICE_API_URL,
    #             json=payload,
    #             timeout=10
    #         )
    #         if response.status_code != 200:
    #             logger.error(f"电话预警失败: {response.text}")
    #         return response.status_code == 200
    #     except Exception as e:
    #         logger.error(f"电话预警失败: {e}")
    #         return False

    @staticmethod
    def send_voice_call(mobile, param):
        host = Config.VOICE_API_URL
        path = Config.VOICE_API_PATH
        url = host + path
        appcode = Config.VOICE_APP_CODE
        templateId = Config.TEMPLATE_ID
        bodys = {
            'mobile': mobile,
            'param': "预警任务,"+param,
            'templateId': templateId
        }
        try:
            response = requests.post(url, data=bodys, headers={
                'Authorization': f'APPCODE {appcode}',
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            })
            logger.info("电话预警:%s"%response.text)
            return response.status_code==200
        except requests.exceptions.RequestException as e:
            logger.error(f"电话预警失败: {e}")
            return False
    @staticmethod
    def send_email(email, subject, message):
        """发送邮件预警（示例）"""
        # 实现邮件发送逻辑
        pass

    def notify(self, rule: AlertRule, actual_value,standard_value,base_dict):
        owners = rule.owner.split(',')
        message = (
            f"规则触发: {rule.rule_name}\n"
            f"当前值: {actual_value} {rule.operator} {standard_value}\n"
            f"######################\n"
            f"当前值SQL: {rule.query_sql%(base_dict)}\n\n"
            f"标准值SQL: {rule.standard_value%(base_dict)}\n" )

        # 根据级别选择通知方式
        notification_method = "DingTalk"
        success = False

        if rule.alert_level == 'NORMAL':
            success = self.send_dingtalk(owners, message)
        elif rule.alert_level == 'URGENT':
            # 尝试电话通知
            for owner in owners:
                if owner.strip().isdigit() and len(owner.strip()) == 11:
                    success = self.send_voice_call(owner.strip(), "%s,%s"%(rule.rule_name,actual_value) )
                    notification_method = "VoiceCall"
                    if success:
                        break
            # 如果电话通知失败，降级为钉钉
            #if not success:
            if True:
                success = self.send_dingtalk(owners, message)
                notification_method = "DingTalk"
        else:  # CRITICAL
            # 关键级别：电话+钉钉
            phone_success = False
            for owner in owners:
                if owner.strip().isdigit() and len(owner.strip()) == 11:
                    if self.send_voice_call(owner.strip(), message):
                        phone_success = True
            ding_success = self.send_dingtalk(owners, message)
            success = phone_success or ding_success
            notification_method = "VoiceCall+DingTalk"

        return success, notification_method